package com.orqlog.timedorder.config;

import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

//    @Bean
//    public Queue queueTTLWaiting() {
//        Map<String, Object> props = new HashMap<>();
//        // 设置等待2s
//        props.put("x-message-ttl", 20000);
//        Queue queue = new Queue("q.pay.ttl-waiting", false, false, false, props);
//        return queue;
//    }
//
//    @Bean
//    public Queue queueWaiting() {
//        Queue queue = new Queue("q.pay.waiting", false, false, false);
//        return queue;
//    }
//
//    @Bean
//    public Exchange exchangeTTLWaiting() {
//        DirectExchange exchange = new DirectExchange("ex.pay.ttl-waiting", false, false);
//        return exchange;
//    }

    /**
     * 该交换器使用的时候，需要给每个消息设置有效期
     */
//    @Bean
//    public Exchange exchangeWaiting() {
//        DirectExchange exchange = new DirectExchange("ex.pay.waiting", false, false);
//        return exchange;
//    }
//
//    @Bean
//    public Binding bindingTTLWaiting() {
//        return BindingBuilder.bind(queueTTLWaiting()).to(exchangeTTLWaiting()).with("pay.ttl-waiting").noargs();
//    }
//
//    @Bean
//    public Binding bindingWaiting() {
//        return BindingBuilder.bind(queueWaiting()).to(exchangeWaiting()).with("pay.waiting").noargs();
//    }

    /**
     * 支付队列
     * @return
     */
    @Bean
    public Queue queuePay() {
        Map<String, Object> props = new HashMap<>();
        // 消息生存时间
        props.put("x-message-ttl", 10000);
        props.put("x-dead-letter-exchange", "ex.pay.dlx");
        props.put("x-dead-letter-routing-key", "pay.dlx");

        Queue queue = new Queue("q.pay", true, false, false, props);
        return queue;
    }

    /**
     * 支付死信队列
     * @return
     */
    @Bean
    public Queue queuePayDlx() {
        Queue queue = new Queue("q.pay.dlx", true, false, false);
        return queue;
    }

    /**
     * 支付交换器
     * @return
     */
    @Bean
    public Exchange exchangePay() {
        DirectExchange exchange = new DirectExchange("ex.pay", true, false, null);
        return exchange;
    }

    /**
     * 支付死信交换器
     */
    @Bean
    public Exchange exchangePayDlx() {
        DirectExchange exchange = new DirectExchange("ex.pay.dlx", true, false, null);
        return exchange;
    }

    /**
     * 绑定支付队列与支付交换器
     * @return
     */
    @Bean
    public Binding bindingPay() {
        return BindingBuilder.bind(queuePay()).to(exchangePay()).with("pay").noargs();
    }

    /**
     * 绑定支付死信交换器和死信队列
     */
    @Bean
    public Binding bindingPayDlx() {
        return BindingBuilder.bind(queuePayDlx()).to(exchangePayDlx()).with("pay.dlx").noargs();
    }
}
